//-------------------------------------------------------------------------
// Copyright (c) 2000-2010 Ufinity. All Rights Reserved.
//
// This software is the confidential and proprietary information of
// Ufinity
//
// Original author: Administrator
//
//-------------------------------------------------------------------------
// UFINITY MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
// THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UFINITY SHALL NOT BE
// LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
// MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
//
// THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
// CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
// PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
// NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
// SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
// SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
// PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). UFINITY
// SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
// HIGH RISK ACTIVITIES.
//-------------------------------------------------------------------------
package com.password.safe.component;

import java.awt.Color;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import com.password.safe.constants.Constants;
import com.password.safe.controller.LoginController;
import com.password.safe.dto.Messages;
import com.password.safe.util.LoginObserver;


public class LoginFrame extends JFrame implements LoginObserver {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(LoginFrame.class);

	private LoginController loginController;
	
	private int loginFailedTimes;

    private JLabel usernameLabel;
    JTextField username;
    private JLabel passwordLabel;
    private JPasswordField password;
    
    private LoginFrame(String title) {
        super(title);
        this.getContentPane().setLayout(null);
        // 下面两行是取得屏幕的高度和宽度
        double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        this.setLocation(new Point((int) (lx / 2) - 150, (int) (ly / 2) - 200));// 设定窗口出现位置
        this.setSize(340, 240);// 设定窗口大小
        showWin();
    }

    private void showWin() {

        // 确保窗体有一个好的外观装饰
        //setDefaultLookAndFeelDecorated(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        // 姓名
        usernameLabel = new JLabel(Constants.LABEL_USERNAME);
        usernameLabel.setBounds(30, 10, 60, 25);
        username = new JTextField();
        username.setBounds(100, 10, 120, 20);
        username.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        username.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {
            	// auto submit
            	if (Constants.KEY_CODE_ENTER == e.getKeyCode()) {
            		login();
            	}
            }

            public void keyTyped(KeyEvent e) {
                if (username.getText().length() > 6) {
                    username.setText(username.getText().substring(0, 6));
                }
            }
        });
        username.addMouseListener(new MouseListener() {
			
			public void mouseReleased(MouseEvent e) {
				getUsername().setText("");
				getUsername().setBackground(getPassword().getBackground());
			}
			
			public void mousePressed(MouseEvent e) {
			}
			
			public void mouseExited(MouseEvent e) {
			}
			
			public void mouseEntered(MouseEvent e) {
			}
			
			public void mouseClicked(MouseEvent e) {
			}
		});
        
        passwordLabel = new JLabel(Constants.LABEL_PASSWORD);
        passwordLabel.setBounds(30, 40, 50, 25);
        password = new JPasswordField();
        password.setBounds(100, 40, 120, 20);
        password.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        password.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {
            	// auto submit
            	if (Constants.KEY_CODE_ENTER == e.getKeyCode()) {
            		login();
            	}
            }

            public void keyTyped(KeyEvent e) {
                if (getPassword().getText().length() > Constants.PASSWORD_MAX_LENGTH) {
                	getPassword().setText(getPassword().getText().substring(0, Constants.PASSWORD_MAX_LENGTH));
                }
            }
        });

        // 确定按钮
        JButton ok = new JButton(Constants.BUTTON_CONFIRM);
        ok.setBounds(50, 90, 60, 25);
        ok.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
            	login();
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
            }
        });

        // 取消按钮
        JButton cancel = new JButton(Constants.BUTTON_CANCEL);
        cancel.setBounds(120, 90, 60, 25);
        cancel.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
                username.setText("");
                getPassword().setText("");
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
            }
        });

        this.getContentPane().add(usernameLabel);
        this.getContentPane().add(username);
        this.getContentPane().add(passwordLabel);
        this.getContentPane().add(password);
        this.getContentPane().add(ok);
        this.getContentPane().add(cancel);
    }
    
    void login() {
		String uname = username.getText();
    	String upassword = String.valueOf(password.getPassword());
    	loginController.doLogin(uname, upassword);
	}
    
	public JTextField getUsername() {
		return username;
	}

	public JTextField getPassword() {
		return password;
	}

	public void loginSuccess(Messages messages) {
		logger.debug("login success, hidden login frame...");
		this.setVisible(false);
	}

	public void loginFailed(Messages messages) {
		if (messages.getMessage(Constants.MSG_KEY_LOGOUT) == null) {
			++loginFailedTimes;
			logger.debug("have failed " + loginFailedTimes + "times");
			getUsername().setText(Constants.ERROR_MSG_INVALIDATE_USER);
			getUsername().setBackground(Color.RED);
		} else {
			logger.debug("logout request, show login frame...");
			getUsername().setText("");
		}
		getPassword().setText("");
		this.setVisible(true);
	}
	
	public LoginController getLoginController() {
		return loginController;
	}

	public void setLoginController(LoginController loginController) {
		this.loginController = loginController;
		// register observer
        loginController.addLoginObserver(this);
	}
	
}
